import { computed, ref } from "vue";

// 2、实现获取焦点
export function useElementFocus(data, previewRef, callBack) {

    let selectBlockIndex = ref(-1)

    let lastSelectBlock = computed(() => data.value.blocks[selectBlockIndex.value])

    // 获取选中的元素和没有被选中的元素
    const focusData = computed(() => {
        let focused = []
        let unFocused = []
        data.value.blocks.forEach((block) => (block.focus ? focused : unFocused).push(block))
        return {
            focused,
            unFocused
        }
    })

    // 清空所有的焦点
    const clearBlockAllFocus = () => {
        data.value.blocks.forEach((block) => block.focus = false)
    }

    // 按下鼠标选择元素
    const onBlockMousedown = (e, block, index) => {
        if (previewRef.value) return
        e.preventDefault();
        e.stopPropagation();
        if (e.shiftKey) {
            if (focusData.value.focused.length <= 1) {
                block.focus = true
            } else {
                block.focus = !block.focus
            }
        } else {
            if (!block.focus) {
                // 先清空所有的focus
                clearBlockAllFocus()
                block.focus = true
            }
        }
        selectBlockIndex.value = index;
        callBack(e)
    }

    // 点击盒子 取消所有选中的元素
    const onContainerMousedown = () => {
        if (previewRef.value) return
        clearBlockAllFocus()
        selectBlockIndex.value = -1
    }
    return {
        focusData,
        onBlockMousedown,
        onContainerMousedown,
        clearBlockAllFocus,
        lastSelectBlock,
    }
}